import 'package:casdon/core/logger/log.dart';
import 'package:casdon/modules/demo/data/repository/demo_repository_impl.dart';
import 'package:casdon/modules/demo/ui/screen/demo_sse_text_utitls.dart';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_markdown/flutter_markdown.dart'; // 导入 markdown 渲染库

class DemoSseTextScreen extends ConsumerStatefulWidget {
  final String text;

  const DemoSseTextScreen({super.key, required this.text});

  @override
  _DemoSseTextScreenState createState() => _DemoSseTextScreenState();
}

class _DemoSseTextScreenState extends ConsumerState<DemoSseTextScreen> {
  bool _connected = false;
  StringBuffer _messageBuffer = StringBuffer(); // 用来拼接接收到的消息内容

  @override
  void initState() {
    super.initState();
    _sseStream(widget.text);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('AI 菜谱推荐')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const SizedBox(height: 20),

            if (_connected) ...[
              const SizedBox(height: 20),
              // const Text("连接成功！"),
            ],
            const SizedBox(height: 20),
            Expanded(
              child: SingleChildScrollView(
                child: MarkdownBody(
                  data: _messageBuffer.toString(), // 展示拼接后的 Markdown 内容
                ),
              ),
            ),
            const SizedBox(height: 20),
          ],
        ),
      ),
    );
  }

  _sseStream(String text) async {
    startSSEAIRecipe(
      onDone: () => _onDone(),
      onError: (e) => _onError(e),
      onMessage: (data) => _onMessage(data),
      onConnectSuccess: () => _onConnectSuccess(ref, text),
      text: text,
    );
  }

  _onDone() {
    // 连接关闭后的处理
    setState(() {
      _connected = false;
    });
  }

  _onError(Exception e) {
    // 错误处理
    // Log.e("SSE Error = $e");
  }

  _onMessage(String data) {
    data = data.trim();
    String filtered1 = data.replaceAll(':connected', '');
    String filtered2 = filtered1.replaceAll('event:message\ndata:', '');
    String filtered = filtered2.replaceAll('data:', '');
    Log.i(filtered);
    setState(() {
      _messageBuffer.write(filtered);
    });
  }

  _onConnectSuccess(WidgetRef ref, String url) {
    // 连接成功时的处理，只执行一次
    if (!_connected) {
      setState(() {
        _connected = true;
        _messageBuffer.clear();
        _messageBuffer = StringBuffer();
      });
    }
    ref.read(demoRepositoryProvider).getAIRecipe(widget.text);
  }
}
